const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');  
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.resolve(__dirname, 'public')));
let users = [{ username: 'a', password: '123456', avatar: 'http://cn.gravatar.com/avatar/01459f970ce17cd9e1e783160ecc951a' }, { username: 'b', password: '123456', avatar: 'http://cn.gravatar.com/avatar/01459f970ce17cd9e1e783160ecc951a' }];
// let userSessions = {};
app.get('/',function (req,res) {
     res.end('hello  world')
})
app.post('/api/login', function (req, res) {
    let body = req.body;
    let user;
    for (let i = 0; i < users.length; i++) {
        if (body.username == users[i].username && body.password == users[i].password) {
            user = users[i];
            console.log(user)
            break;
        }
    }
    if (user) {
        console.log(111)
        const sessionId = 'user_' + Math.random() * 1000;
        // res.cookie('username', user.username);
        res.cookie("name",'zhangsan',{maxAge: 900000});  
        // res.cookie('sessionId', sessionId, { httpOnly: true });
        // userSessions[sessionId] = {};
        res.json({ code: 0, user });
    } else {
        res.json({ code: 1, data: '没有该用户' });
    }
});
// app.get('/api/user', function (req, res) {
//     let { username } = userSessions[req.cookies.sessionId];
//     if (username) {
//         let user;
//         for (let i = 0; i < users.length; i++) {
//             if (username == users[i].username) {
//                 user = users[i];
//                 break;
//             }
//         }
//         res.json({ code: 0, user });
//     } else {
//         res.json({ code: 1, error: '用户没有登录' });
//     }
// });

// app.post('/api/transfer', function (req, res) {
//     let { target, amount } = req.body;
//     amount = isNaN(amount) ? 0 : Number(amount);
//     let { username } = userSessions[req.cookies.sessionId];
//     if (username) {
//         let user;
//         for (let i = 0; i < users.length; i++) {
//             if (username == users[i].username) {
//                 users[i].money -= amount;
//             } else if (target == users[i].username) {
//                 users[i].money += amount;
//             }
//         }
//         res.json({ code: 0 });
//     } else {
//         res.json({ code: 1, error: '用户没有登录' });
//     }
// })
app.listen(3000, () => console.log('服务启动在3000端口'));